<template>
    <div class="wrapper">
        <div style="margin: 150px auto; background-color: #fff; width: 350px; height: 420px;border-radius: 10px; ">
            <div class="login-top"><b>西华大学在线考试登录</b></div>
            <el-form :model="user" :rules="rules" ref="userForm" class="login-form">
                <el-form-item prop="username">
                    <el-input size="medium" placeholder="请输入用户名" style="margin: 10px 0" prefix-icon="el-icon-user"
                              v-model="user.userId"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input placeholder="请输入密码" size="medium" style="margin: 10px 0" prefix-icon="el-icon-lock"
                              show-password
                              v-model="user.password"></el-input>
                </el-form-item>
                <el-form-item prop="code">
                    <el-row :gutter="20">
                        <el-col :span="14">
                            <div class="grid-content bg-purple">
                                <el-input placeholder="请输入验证码" size="medium" style="margin: 10px 0"
                                          prefix-icon="el-icon-key"
                                          v-model="user.code"></el-input>
                            </div>
                        </el-col>
                        <el-col :span="10">
                            <div class="grid-content bg-purple">
                                <div>
                                    <canvas id="canvas"
                                            style="display: inline-block; float: right; width: 120px; height: 60%;"></canvas>
                                </div>
                            </div>
                        </el-col>
                    </el-row>


                </el-form-item>
                <el-form-item style="margin: 10px 0; text-align: right">
                    <el-button type="primary" @click="login">登 录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<style>
    .wrapper {
        background: url("../assets/img/login-bg.jpg");
        background-size: 150% 150%;
        width: 100%;
        height: 100%;
        position: fixed;

    }

    .login-top {
        padding: 0;
        border-radius: 0;
        font-size: 30px;
        line-height: 117px;
        text-align: center;
        font-weight: 400;
        color: #fff;
        background-color: #148be4;
        border-radius: 12px 12px 0 0;

    }

    .login-form {
        padding: 20px;
    }

    .login-form .el-input__inner {
        border-radius: 10px;
    }
</style>
<script>
    import {setRoutes} from "@/router";
    import $ from 'jquery'

    export default {
        name: "Login",
        data() {
            return {
                user: {},
                code: "",
                rules: {
                    userId: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, max: 13, message: '长度在 6 到 13 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 1, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
                    ],
                },
            }
        },
        created() {
            this.user = {
                userId: "123456",
                password: "123456",
                code: this.code
            }
        },
        mounted() {
            this.code = this.draw()
          this.user.code = this.code;
        },
        methods: {
            login() {
                if (this.user.code != this.code) {
                    this.$message.error("验证码错误，请重新输入！！！")
                    this.user["code"] = "";
                    this.code = this.draw() //刷新验证码
                    return;
                }
                // 表单校验合法
                this.$refs['userForm'].validate((valid) => {
                    if (valid) {
                        this.request.post("/user/login", this.user).then(res => {
                            if (res.code === '200') {
                                localStorage.setItem("user", JSON.stringify(res.data))  // 存储用户信息到浏览器
                                localStorage.setItem("menus", JSON.stringify(res.data.menus))  // 存储用户信息到浏览器
                                // 动态设置当前用户的路由
                                setRoutes()
                                this.$message.success("登录成功")
                                this.$router.push("/")
                            } else {
                                this.$message.error(res.msg)
                            }
                        }).catch((err) => {
                            this.$message.error(err);
                        })
                    }
                });
            },
            draw() {
                var show_num = [];
                var canvas_width = $('#canvas').width();
                var canvas_height = $('#canvas').height();
                var canvas = document.getElementById("canvas");//获取到canvas的对象，演员
                var context = canvas.getContext("2d");//获取到canvas画图的环境，演员表演的舞台
                canvas.width = canvas_width;
                canvas.height = canvas_height;
                var sCode = "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
                var aCode = sCode.split(",");
                var aLength = aCode.length;//获取到数组的长度

                for (var i = 0; i <= 3; i++) {
                    var j = Math.floor(Math.random() * aLength);//获取到随机的索引值
                    var deg = Math.random() * 30 * Math.PI / 180;//产生0~30之间的随机弧度
                    var txt = aCode[j];//得到随机的一个内容
                    show_num[i] = txt.toLowerCase();
                    var x = 10 + i * 25;//文字在canvas上的x坐标
                    var y = 33 + Math.random() * 8;//文字在canvas上的y坐标
                    context.font = "bold 23px 微软雅黑";
                    context.translate(x, y);
                    context.rotate(deg);
                    context.fillStyle = this.randomColor();
                    context.fillText(txt, 0, 0);
                    context.rotate(-deg);
                    context.translate(-x, -y);
                }
                for (var i = 0; i <= 5; i++) { //验证码上显示线条
                    context.strokeStyle = this.randomColor();
                    context.beginPath();
                    context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
                    context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
                    context.stroke();
                }
                for (var i = 0; i <= 30; i++) { //验证码上显示小点
                    context.strokeStyle = this.randomColor();
                    context.beginPath();
                    var x = Math.random() * canvas_width;
                    var y = Math.random() * canvas_height;
                    context.moveTo(x, y);
                    context.lineTo(x + 1, y + 1);
                    context.stroke();
                }
                // $("#test0").val();//保存变量
                console.log("show", show_num)
                return show_num.join('')
            },
            randomColor() {//得到随机的颜色值
                var r = Math.floor(Math.random() * 256);
                var g = Math.floor(Math.random() * 256);
                var b = Math.floor(Math.random() * 256);
                return "rgb(" + r + "," + g + "," + b + ")";
            },

        }

    }
</script>
